package m2;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Consumer {
    public static void main(String[] args) throws IOException, TimeoutException {
        // 1.连接
        ConnectionFactory f = new ConnectionFactory();
        f.setHost("192.168.64.140");   // wht6.cn
        f.setPort(5672);
        f.setUsername("admin");
        f.setPassword("admin");
        Connection con = f.newConnection(); //连接
        Channel c = con.createChannel();    //通信通道

        // 2.创建 helloworld 队列
        c.queueDeclare("task_queue", true, false, false, null);

        // 创建回调对象
        DeliverCallback deliverCallback = new DeliverCallback() {
            @Override
            public void handle(String consumerTag, Delivery message) throws IOException {
                byte[] body = message.getBody();
                String msg = new String(body);
                System.out.println("收到： " + msg);
                for (int i = 0; i < msg.length(); i++) {
                    if (msg.charAt(i) == '.') {
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
                c.basicAck(message.getEnvelope().getDeliveryTag(), false);
                System.out.println("消息处理完成");
            }
        };
        CancelCallback cancelCallback = new CancelCallback() {
            @Override
            public void handle(String consumerTag) throws IOException {

            }
        };
        // 3.接收消费数据，收到的数据要交给一个回调对象进行处理
        c.basicQos(1);
        /*
        第二个参数
            true: 自动ack(acknowledgement， 自动确认)
            false: 手动ack
         */
        c.basicConsume("task_queue", false, deliverCallback, cancelCallback);
    }
}
